<?php 
class CategoryController extends CommonController{
	//添加方法
	public function add(){
		if(IS_POST){
			// p($_POST);die;
			$cate=M('category');
			$re=$cate->add($_POST);
			if($re){
				$this->success('添加成功',U('Category/index'));
			}else{
				$this->error('添加失败',U('Category/add'));
			}
		}else{
			// p($_GET);
			if(isset($_GET['pid'])){
				$pid=intval($_GET['pid']);
			}else{
				$pid=0;
			}
			// echo $pid;
			$this->assign('pid',$pid);
			$this->display();
		}
		
	}
//列表方法
	public function index(){
		$cate=M('category');
		$cateData=$cate->all();
		
		$cateData = Data::tree($cateData,'cname');
		// p($cateData);die;
		$this->assign('cateData',$cateData);
		$this->display();
	}
	
	//删除方法 
	public function del(){
		$cid=intval($_GET['cid']);
		$cate=M('category');
		$re=$cate->where(array('cid'=>$cid))->del();
		if($re){
			$this->success('删除成功',U('Category/index'));
		}else{
			$this->error('删除失败',U('Category/index'));
		}
	}
	//修改方法
	public function edit(){
		$cate=M('category');
		if(IS_POST){
			// p($_POST);
			$cid=$_POST['cid'];
			$re=$cate->where(array('cid'=>$cid))->save();
				if($re){
				$this->success('修改成功',U('Category/index'));
				}else{
					$this->error('修改失败',U('Category/index'));
				}
		}else{
			$cid=intval($_GET['cid']);
			$cateData_all=$cate->field('cid,cname,pid')->all();//查询所有
			$this->assign('cateData_all',$cateData_all);
			$cateData=$cate->where(array('cid'=>$cid))->all();
			// p($cateData);
			$this->assign('cateData',$cateData);
			$this->display();
		}
	}

	//更新缓存
	public function cache(){
		$model=M('category');
		$re=$model->cacheData();
		p($re);
		// $re = $this->model->cacheData();
		if($re){
			$this->success('更新缓存成功','category/index');
		}else{
			$this->error('更新失败','category/index');
		}
	}
//排序
	public function sort(){
		if(IS_POST){
			// p($_POST);
			$model=M('category');
			$data=array();
			// $data=array('cid'=>9,'sort'=>'5');
			foreach ($_POST['cid'] as $k=> $v) {
				$data[$v]=$_POST['sort'][$k];
			}

			// p($data);die;
			foreach ($data as $key => $value) {
				$arr=array('cid'=>$key,'sort'=>$value);
				$result=$model->save($arr);	
			}
			if($result){
				$this->success('修改成功','category/index');
			}
		}
	}


}


 ?>